#!/bin/bash

# For the license, see the LICENSE file in the root directory.
#set -x

ROOT=${abs_top_builddir:-$(pwd)/..}
TESTDIR=${abs_top_testdir:-$(dirname "$0")}

PATH=$ROOT/src/swtpm:$PATH

source "${TESTDIR}/common"
[ "${SWTPM_IFACE}" == "cuse" ] && source "${TESTDIR}/test_cuse"

trap "cleanup" SIGTERM EXIT

function cleanup()
{
	if [ -n "${SWTPM_PID}" ]; then
		kill_quiet -9 "${SWTPM_PID}"
	fi
	rm -rf "${workdir}"
}

# Test 1: No states

workdir="$(mktemp -d)" || exit 1
if ! msg="$(${SWTPM_EXE} "${SWTPM_IFACE}" --print-states --tpmstate "dir=${workdir}" 2>&1)"; then
	echo "Error: Could not pass --print-states"
	echo "${msg}"
	exit 1
fi

exp='\{ "type": "swtpm", "states": \[\] \}'
if ! [[ ${msg} =~ ${exp} ]]; then
	echo "Unexpected response from ${SWTPM_IFACE} TPM to --print-states:"
	echo "Actual   : ${msg}"
	echo "Expected : ${exp}"
	echo "Test 1: Failed"
	exit 1
fi

echo "Test 1: OK"
cleanup

# Test 2: Existing state

workdir="$(mktemp -d)" || exit 1
statefile="${workdir}/tpm-00.permall"
dummydata="DUMMY"
echo "$dummydata" > "${statefile}"

if ! msg="$(${SWTPM_EXE} "${SWTPM_IFACE}" --print-states --tpmstate "dir=${workdir}" 2>&1)"; then
	echo "Error: Could not pass --print-states"
	echo "${msg}"
	exit 1
fi

exp='\{ "type": "swtpm", "states": \[ \{"name": "permall", "size": 6\} \] \}'
if ! [[ ${msg} =~ ${exp} ]]; then
	echo "Unexpected response from ${SWTPM_IFACE} TPM to --print-states:"
	echo "Actual   : ${msg}"
	echo "Expected : ${exp}"
	exit 1
fi

echo "Test 2: OK"

if [ "${SWTPM_IFACE}" = socket ]; then
	# Test 3: Running swtpm that holds lock on .lock; swtpm --print-states not locked out
	rm -f "${workdir}/"*
	run_swtpm "${SWTPM_INTERFACE}" --tpmstate "dir=${workdir}"

	if ! kill_quiet -0 "${SWTPM_PID}"; then
		echo "Error: ${SWTPM_INTERFACE} TPM did not start."
		exit 1
	fi

	if ! msg="$(${SWTPM_EXE} "${SWTPM_IFACE}" --print-states --tpmstate "dir=${workdir}" 2>&1)"; then
		echo "Error: Could not pass --print-states"
		echo "${msg}"
		exit 1
	fi

	exp='\{ "type": "swtpm", "states": \[\] \}'
	if ! [[ ${msg} =~ ${exp} ]]; then
		echo "Unexpected response from ${SWTPM_IFACE} TPM to --print-states:"
		echo "Actual   : ${msg}"
		echo "Expected : ${exp}"
		exit 1
	fi

	# Init the TPM
	if ! run_swtpm_ioctl "${SWTPM_INTERFACE}" -i; then
		echo "Error: ${SWTPM_INTERFACE} TPM initialization failed."
		exit 1
	fi

	if ! msg="$(${SWTPM_EXE} "${SWTPM_IFACE}" --print-states --tpmstate "dir=${workdir}" 2>&1)"; then
		echo "Error: Could not pass --print-states"
		echo "${msg}"
		exit 1
	fi

	exp='\{ "type": "swtpm", "states": \[ \{"name": "permall", "size": 1185\} \] \}'
	if ! [[ ${msg} =~ ${exp} ]]; then
		echo "Unexpected response from ${SWTPM_IFACE} TPM to --print-states:"
		echo "Actual   : ${msg}"
		echo "Expected : ${exp}"
		exit 1
	fi

	echo "Test 3: OK"
else
	echo "Test 3: Skipped"
fi

cleanup
exit 0
